/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.multishop.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.DeliveryOrderParam;
import com.yami.shop.bean.param.OrderParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * @author lgh on 2018/09/15.
 */
@Controller
@RequestMapping("/order/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private OrderRefundService orderRefundService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Order>> page(OrderParam orderParam,PageParam<Order> page) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        orderParam.setShopId(shopId);
        orderParam.setLang(I18nMessage.getDbLang());
        IPage<Order> orderPage = orderService.pageOrdersDetailByOrderParam(page, orderParam);
        return ResponseEntity.ok(orderPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
    public ResponseEntity<Order> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber, I18nMessage.getDbLang());
        order.setOrderItems(orderItems);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        return ResponseEntity.ok(order);
    }

    /**
     * 发货
     */
    @PutMapping("/delivery")
    public ResponseEntity<Void> delivery(@RequestBody DeliveryOrderParam deliveryOrderParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(deliveryOrderParam.getOrderNumber(),shopId,true);
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value()) && Objects.equals(order.getDvyType(), DvyType.STATION.value())){
            // 订单不处于待入库状态，无法进行入库
            throw new YamiShopBindException("yami.order.status.no.right");
        }else if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())){
            // 订单不处于待发货状态，无法进行发货
            throw new YamiShopBindException("yami.order.delivery.no.right");
        }
        List<OrderRefund> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());

        if (CollectionUtil.isNotEmpty(orderRefunds)) {
            // 该订单有退款信息正在处理当中，请处理完毕之后再进行发货的操作!
            throw new YamiShopBindException("yami.order.delivery.refund.error");
        }

        Order orderParam = new Order();
        orderParam.setOrderId(order.getOrderId());
        if (!Objects.equals(order.getDvyType(), DvyType.STATION.value()) || !Objects.equals(order.getDvyType(), DvyType.NOT_DELIVERY.value())){
            orderParam.setDvyId(deliveryOrderParam.getDvyId());
            orderParam.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        }
        orderParam.setDvyTime(new Date());
        orderParam.setUpdateTime(new Date());
        orderParam.setStatus(OrderStatus.CONSIGNMENT.value());
        orderParam.setUserId(order.getUserId());

        orderService.delivery(orderParam);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(deliveryOrderParam.getOrderNumber(), I18nMessage.getDbLang());
        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
            productService.removeProdCacheByProdId(orderItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(),orderItem.getProdId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
            skuService.removeSkuCacheBySkuIdAndLang(orderItem.getSkuId(),orderItem.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
        }

        return ResponseEntity.ok().build();
    }
    /**
     * 修改订单金额
     */
    @PutMapping("/changeAmount")
    public ResponseEntity<Void> changeAmount(@RequestBody Order order) {
        if(order.getFreightAmount()<0){
            // 运费不能小于零
            throw new YamiShopBindException("yami.product.dvy.fee");
        }
        if(Objects.isNull(order.getFreightAmount())){
            order.setFreightAmount(0.00);
        }
        orderService.changeAmount(order);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改用户订单地址
     *
     * @param order
     * @return 是否修改成功
     */
    @SysLog("修改用户订单地址")
    @PutMapping("/changeUserAddr")
    public ResponseEntity<String> changeUserAddr(@RequestBody @Valid Order order) {
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderId, order.getOrderId())
                .eq(Order::getOrderNumber,order.getOrderNumber())
        );
        if (orderDb.getStatus() <= OrderStatus.PADYED.value() || Objects.equals(orderDb.getStatus(),OrderStatus.WAIT_GROUP.value())){
            UserAddrOrder userAddrOrder = order.getUserAddrOrder();
            userAddrOrderService.updateById(userAddrOrder);
        }else {
            // 订单状态异常，无法更改订单地址
            throw new YamiShopBindException("yami.order.status.error");
        }
        // 修改成功
        return ResponseEntity.ok().body(I18nMessage.getMessage("yami.activity.update.success"));
    }

    /**
     * 修改订单备注
     *
     * @param order
     * @return 是否修改成功
     */
    @SysLog("修改订单备注")
    @PutMapping("/changeOrderRamark")
    public ResponseEntity<String> changeOrderRamark(@RequestBody @Valid Order order) {
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderId, order.getOrderId())
                .eq(Order::getOrderNumber,order.getOrderNumber())
        );
        orderDb.setShopRemarks(order.getShopRemarks());
        orderService.updateById(orderDb);
        // 修改成功
        return ResponseEntity.ok().body(I18nMessage.getMessage("yami.activity.update.success"));
    }

    /**
     * 已销售订单
     *
     * @param orderParam
     */
    @GetMapping("/soldExcel")
    public void soldExcel(OrderParam orderParam, HttpServletResponse response) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        orderParam.setShopId(shopId);
        orderService.soldExcel(orderParam,response);
    }

}
